<template>
  <div class="home"> 
    <div class="chart" ref="chart">

    </div>
    
    </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import dayjs from 'dayjs'
import { totaldata } from '../../api/account';

// 获取dom
const chart = ref(null)

//echarts 实例对象
let myChart  = null;
const data = ref({})

const draw = () => {
  myChart = echarts.init(chart.value)
  const option = {
    title: {
      text: '数据统计',
      subtext: '日期:' + dayjs().format('YYYY-MM-DD'),
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['订单', '销售额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.value.xData || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单',
        type: 'line',
        stack: 'Total',
        data: data.value.orderData || []
      },
      {
        name: '销售额',
        type: 'line',
        stack: 'Total',
        data: data.value.amountData || []
      }
    ]
  };
  myChart.setOption(option)
}

onMounted(() => {
  const getData = () => {
    totaldata().then(res => {
      console.log(res);
      data.value = res
      draw()
    })
  }
  getData();
})

// 监听页面的宽高变化 
const getsize = () => {
    console.log('宽高发生了改变');
    myChart.resize()
}
window.addEventListener('resize', getsize)

// 销毁页面 取消监听window事件
onBeforeUnmount(() => {
  if (myChart) {
    window.removeEventListener('resize', getsize);
    myChart.dispose(); // 销毁 ECharts 实例
  }
})

</script>

<style scoped lang="scss">
.chart{
  width: 100%;
  height: 100%;
}
.home{
  width: 100%;
  height: 100vh;
}
</style>    